package com.ruoyi.web.controller.open;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.model.LoginDTO;
import com.ruoyi.common.core.page.ResultEntity;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MinioTemplate;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IAiAlarmDataService;
import com.ruoyi.system.service.ITDeviceHandleLogService;
import com.ruoyi.system.service.ITProdRecordService;
import com.ruoyi.system.service.TDeviceV2LineWarnRecordService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.Date;
import java.util.Objects;

/**
 * @author wux
 * @date 2023/7/11 14:46
 */
@Slf4j
@RestController
@RequestMapping("/client/open")
public class ForeignOpenClient {
    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private MinioTemplate minioTemplate;
    @Autowired
    private IAiAlarmDataService aiAlarmDataService;
    @Autowired
    private TDeviceV2LineWarnRecordService deviceV2LineWarnRecordService;
    @Autowired
    private ITProdRecordService recordService;
    @Autowired
    private ITDeviceHandleLogService itDeviceHandleLogService;
    @Autowired
    private RedisCache redisCache;

    @PostMapping("/upload")
    @ApiOperation(value = "文件上传")
    public ResultEntity upload(@RequestParam("file") MultipartFile file) throws Exception {
        return ResultEntity.createSuccess(minioTemplate.upload(file));
    }

    /**
     * 网关登录验证
     * @param params
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "获取token")
    public ResultDevice login(@Valid @RequestBody LoginDTO params) {
        // 生成令牌
        params.setChannel(2);
        try {
            String token = sysLoginService.login(params);
            return ResultDevice.ok(token, 30 * 60);
        } catch (Exception e) {
            return ResultDevice.error(1);
        }
    }

    /**
     * 生产记录上传
     * @param params
     * @return
     */
    @PostMapping("/up/prodRecord")
    public ResultDevice uploadRecord(@RequestBody String params, @RequestHeader("token") String token) {
        if(StringUtils.isBlank(token)){
            return ResultDevice.error(1);
        }
        System.out.println(params);
        JSONObject result = JSONObject.parseObject(params);
        JSONObject data = result.getJSONObject("data");
        String deviceId = result.get("deviceId").toString();
        switch (deviceId){
            //根据产线处理生产记录和报警
            case "ggjhj":
                if(data.containsKey("hhjbj")){
                    TDeviceV2LineWarnRecord warnRecord = new TDeviceV2LineWarnRecord();
                    warnRecord.setLine("ggj_line");
                    warnRecord.setContent("钢拱架焊接机预警!");
                    warnRecord.setWarnType("abnormal_alarm");
                    warnRecord.setWarnTime(new Date());
                    deviceV2LineWarnRecordService.save(warnRecord);
                }
                if(data.containsKey("wccl1")){
                    TProdRecord record = new TProdRecord();
                    record.setOperator("设备采集");
                    record.setMadeDate(new Date());
                    int taskNum = recordService.count(new LambdaQueryWrapper<TProdRecord>()
                            .eq(TProdRecord::getProdId,"ggj")
                            .apply("DATE_FORMAT(create_time,'%Y-%m-%d') = CURDATE()"));
//                    record.setProdId();
//                    recordService.save();
                }
                break;
            case "qgjqg":
                if(data.containsKey("qgjbj")){
                    TDeviceV2LineWarnRecord warnRecord = new TDeviceV2LineWarnRecord();
                    warnRecord.setLine("ggj_line");
                    warnRecord.setContent("钢拱架切割机预警!");
                    warnRecord.setWarnType("abnormal_alarm");
                    warnRecord.setWarnTime(new Date());
                    deviceV2LineWarnRecordService.save(warnRecord);
                }
                break;
            case "wp":
                if(data.containsKey("lwsfbj") || data.containsKey("lwxwbj") || data.containsKey("sssfbj")){
                    TDeviceV2LineWarnRecord warnRecord = new TDeviceV2LineWarnRecord();
                    warnRecord.setLine("wp_line");
                    if(data.containsKey("lwsfbj")){
                        warnRecord.setContent("网片生产线拉网伺服报警!");
                    }else if(data.containsKey("lwxwbj")) {
                        warnRecord.setContent("网片生产线拉网限位报警!");
                    }else {
                        warnRecord.setContent("网片生产线送丝伺服报警!");
                    }
                    warnRecord.setWarnType("abnormal_alarm");
                    warnRecord.setWarnTime(new Date());
                    deviceV2LineWarnRecordService.save(warnRecord);
                }
                break;
            case "ljg":
                break;
            case "xdg":
                break;
        }

        return ResultDevice.ok();
    }

//    /**
//     * *************************算能新一代盒子（带预警语音播报功能）2023-10-20*******************************
//     * 第一步：盒子上传报警图片到服务器，对应下面的uploadFile方法
//     * 第二步：推送告警监测信息，对应下面的uploadMsg方法
//     *
//     */
//    @PostMapping("/uploadFile")
//    public Map<String,Object> uploadFile(@RequestParam("file") MultipartFile file) {
//        Map<String,Object> map = new HashMap<>(4);
//        try {
//            String filePath = minioTemplate.upload(file);
//            map.put("url",filePath);
//        } catch (Exception e) {
//            map.put("code",1);
//            map.put("msg","文件上传异常");
//            map.put("url","");
//            map.put("id","");
//            return map;
//        }
//        map.put("code",0);
//        map.put("msg","文件上传成功");
//        map.put("id","");
//        return map;
//    }
//
//
//
//    @PostMapping("/uploadMsg")
//    public void uploadMsg(HttpServletRequest request){
//        try {
//            String projectCode = request.getParameter("proCode");
//            log.info("uploadMsg====proCode:{}",projectCode);
//            StringBuffer sb = new StringBuffer();
//            InputStream is = request.getInputStream();
//            InputStreamReader isr = new InputStreamReader(is);
//            BufferedReader br = new BufferedReader(isr);
//            String s = "";
//            while ((s = br.readLine()) != null) {
//                sb.append(s);
//            }
//            String res = sb.toString();
//            log.info("uploadMsg回调接口接收到数据:{}",res);
//            JSONObject data = JSON.parseObject(res);
//            String deviceId = data.getString("deviceId");
//            Integer timestamp = data.getInteger("timestamp");
//            JSONObject payload = data.getJSONObject("payload");
//            JSONObject msgObj = payload.getJSONObject("msg");
//            String eventCode = msgObj.getString("eventCode");//算法id
//            String eventName = msgObj.getString("eventName");//算法名称
//            JSONArray imgUrls = msgObj.getJSONArray("imgUrls");//报警图片数组
//            String imgUrl =String.valueOf(imgUrls.get(0));
//            AiAlarmData alarmData = new AiAlarmData();
//            alarmData.setProjectId(1L);
//            alarmData.setAlgoId(eventCode);
//            alarmData.setCameraName(eventName);
//            alarmData.setCameraId(deviceId);
//            alarmData.setAlarmPicName("");
//            alarmData.setAlarmPicData(imgUrl);
//            alarmData.setTimestamp(timestamp);
//            log.info("AiAlarmData:{}",alarmData);
//            aiAlarmDataService.save(alarmData);
//        }catch (Exception e){
//            log.error("uploadMsg数据接收处理异常：{}",e.getMessage());
//        }
//    }

    @GetMapping("/xywl/dateSet")
    @ApiOperation(value = "获取下发数据")
    public String dateSet(@RequestParam(value = "gatewayMac") String gatewayMac) {
        TDeviceHandleLog log = itDeviceHandleLogService.getOne(new LambdaQueryWrapper<TDeviceHandleLog>()
                .eq(TDeviceHandleLog::getStatus,0)
                .eq(TDeviceHandleLog::getDeviceNum,gatewayMac)
                .orderByAsc(TDeviceHandleLog::getCreateTime)
                .last("LIMIT 1"));

        if(Objects.isNull(log)){
            JSONObject result = new JSONObject();
            result.put("code",0);
            return result.toString();
        }
        System.out.println("获取下发数据"+log.getMessage());
        log.setStatus(1);
        itDeviceHandleLogService.updateById(log);
        return log.getMessage();
    }

    /**
     * 鲲云新版AI识别盒子，报警信息推送回调
     * @param params
     */
    @PostMapping("/warnInfoCallback")
    public void warnInfoCallback(@RequestBody String params) throws Exception {
        JSONObject warnResult = JSONObject.parseObject(params);
        String fileUrl = minioTemplate.uploadBase64(warnResult.getString("alarm_pic_data") ,warnResult.getString("alarm_pic_name"));
        AiAlarmData alarmData = new AiAlarmData();
        alarmData.setProjectId(1L);
        alarmData.setAlgoId(warnResult.getString("algorithm_name"));
        alarmData.setCameraName(warnResult.getString("camera_name"));
        alarmData.setCameraId(warnResult.getString("camera_id"));
        alarmData.setAlarmPicName(warnResult.getString("alarm_pic_name"));
        alarmData.setAlarmPicData(fileUrl);
        Date warnTime = DateUtils.parseDate(warnResult.getString("timestamp"),"yyyy-MM-dd HH:mm:ss");
        alarmData.setWarnTime(warnTime);
        log.info("AiAlarmData:{}",alarmData);
        aiAlarmDataService.save(alarmData);
        System.out.println(params);
    }

}
